import {Link} from 'react-router-dom';
import {Select, Alert, Input, Modal, Form, Row, Col, Table, Breadcrumb, Icon,Upload ,Button,DatePicker} from 'antd';

const Option = Select.Option;
const FormItem = Form.Item;
import AppService from './../../common/utils/app.service'
import * as Actions from './actions'
import Utils from './../../common/utils/utils'
import * as CONSTANTS from './../../common/utils/constants'
import UploadImage from "./../../common/utils/app.service";
import axios from 'axios'
var Delta = require('quill-delta/lib/delta');
import ReactQuill, {Quill, Mixin, Toolbar} from 'react-quill'
import Moment from 'moment'

const modules = {
    toolbar: {
        container: [
            ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
            ['blockquote', 'code-block'],

            [{'list': 'ordered'}, {'list': 'bullet'}],
            [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
            [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
            // [{ 'direction': 'rtl' }],                         // text direction

            [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
            [{'header': [1, 2, 3, 4, 5, 6]}],

            [{'color': []}, {'background': []}],          // dropdown with defaults from theme
            [{'font': []}],
            [{'align': []}],
            ['link', 'image'],
            // ['video'],
            ['clean']
        ],
        handlers: {
            "image": function () {
                let fileInput = this.container.querySelector('input.ql-image[type=file]');
                if (fileInput == null) {
                    fileInput = document.createElement('input');
                    fileInput.setAttribute('type', 'file');
                    fileInput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon');
                    fileInput.classList.add('ql-image');
                    fileInput.addEventListener('change', () => {
                        if (fileInput.files != null && fileInput.files[0] != null) {
                            var formData = new FormData();
                            formData.append("upfile", fileInput.files[0]);
                            formData.append("withStatus", true);
                            axios.post(UploadImage.uploadImgUrl, formData, {
                                headers: {
                                    'Content-Type': 'multipart/form-data'
                                },
                                responseType: 'json'
                            }).then(res => {
                                if (res.data.errorCode == 0) {
                                    let range = this.quill.getSelection(true);
                                    this.quill.updateContents(new Delta()
                                        .retain(range.index)
                                        .delete(range.length)
                                        .insert({image: res.data.body})
                                        , Quill.sources.USER);
                                } else {
                                    console.error(res.data);
                                }
                            }).catch(e => {
                                console.error(e);
                            });
                        }
                    });
                    this.container.appendChild(fileInput);
                }
                fileInput.click();
            }
        }
    }
}

class SingerDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      detail:{},
        fileList: [],
        previewVisible: false,
        previewImage: '',

        newList:[
            {
                id:0,
                name:'否'
            },
            {
                id:1,
                name:'是'
            }
        ],
        startValue: null,
        endValue: null,
        endOpen: false,
        content:'',
        songTypeList: [],
    }
  }

    pictureChange = ({ fileList }) => {

        this.setState({ fileList });
        console.log(fileList)
    }

    componentWillMount(){
        // let _this = this;
        // Actions.getSongTypeList().then((result) => {
        //     if(result.errorCode === 0) {
        //         this.setState({
        //             songTypeList: result.body
        //         });
        //     }else {
        //         Utils.dialog.error(result.msg)
        //     }
        // });


    }

  componentDidMount() {
    let _this = this, {dispatch, match} = this.props, id = match.params.id;
       location.hash.indexOf('detail') > 0 && _this.getDateils(id);
      //_this.getDateils(id);
    console.log('detail',this.props);


  }

  getDateils = (id) => {
      let _this = this;
    Actions.getQuestionDetail(id).then(response => {
      if (response.errorCode === 0) {
          let fileList = _this.state.fileList;
          let fileList1 = _this.state.fileList1;
          fileList.push({

          });
          let detail=response.body.options
          let myOptions=detail.options;

          this.setState({
            detail:response.body,
        })
      }
    })
  };
    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }
    handleCancel = ()=>{
        this.setState({
            previewVisible: false
        })
    }
    handleSubmit = (e) => {
        e.preventDefault();
        let _this = this , { history} = this.props;


        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
                _this.setState({buttonLoading: true})
                let params = values;
                //debugger
                params.cover = params.cover.file ? params.cover.file.response.body : params.cover;
                // params.isRecommend = parseInt(params.isRecommend.key) == 1 ? true : false;

                _this.props.match.params.id ? _this.updateInformation(params) : _this.addInformation(params)
            }
        });
    }

    addInformation = (params)=>{
        let _this = this , { history} = this.props;
        Actions.addInformation(params).then((res)=>{
            console.log('eeeee')
            console.log(res);
            _this.setState({buttonLoading: false})
            Utils.dialog.success('新增成功',()=>{
                history.push('/information/manager/index')
            });

        })
    };

    updateInformation = (params)=>{
        let _this = this , {history, match} = this.props;
        params.id = match.params.id;
        Actions.updateInformation(params).then((res)=>{
            console.log(res);
            _this.setState({buttonLoading: false})

            Utils.dialog.success('更新成功',()=>{
                history.push('/information/manager/index')
            });

        })
    }



    onChange = (field, value) => {
        this.setState({
            [field]: value,
        });
    }



    // 上传图片之前
  beforeUpload(file) {
    const isLt2M = file.size / 1024 / 1024 < 5;
    if (!isLt2M) {
      Utils.dialog.error('图片大小不能超过2MB!');
    }
    return isLt2M;
  }

  // 图片改变
  shandleChange = (prop, {file, fileList}) => {
    if (file.response && file.response.errorCode === 0) {
      let detail = this.state.detail
      detail[prop] = file.response.body
      this.setState({detail})
    } else if (file.response && file.response.errorCode != 0) {
      Utils.dialog.error(file.response.msg)
    }
  }
  
  // 上传图片时，转换返回的数据
  normFile = (e) => {
    let fileList = e.fileList.filter((file) => {
      if (file.response) {
        if (file.response.errorCode === 0) {
          file.url = file.response.body
          return true;
        }
      }
      return true;
    }).slice(-1);
    return fileList[0].url;
  }

  // 富文本编辑器内容改变
  handleEditorChange = (value) => {
    this.setState({
      content: value
    })
  }


  render() {
    const {match} = this.props;
       const { getFieldDecorator } = this.props.form;
    const {detail ,fileList,previewVisible, previewImage,newList} = this.state
      const uploadButton = (
          <div>
              <Icon type="plus" />
              <div className="ant-upload-text">Upload</div>
          </div>
      );
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 6},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 14},
      },
    };
      const tailFormItemLayout = {
          wrapperCol: {
              xs: {
                  span: 24,
                  offset: 0,
              },
              sm: {
                  span: 14,
                  offset: 6,
              },
          },
      };

      const props = {
        className: "avatar-uploader",
        action: `${UploadImage.uploadImgUrl}`,
        showUploadList: false,
        withCredentials: true,
        beforeUpload: this.beforeUpload.bind(this),
        onChange: this.shandleChange.bind(this, 'cover'),
        name: 'upfile',
        accept: "image/*",
        data: {
          withStatus: true
        },
        headers: {
          'X-Requested-With': null,
        },
        onProgress: null,
      };

      const props1 = {
          action: `${UploadImage.uploadImgUrl}`,
          showUploadList: false,
          withCredentials: true,
          beforeUpload: this.beforeUpload.bind(this),
          onChange: this.shandleChange.bind(this, 'src'),
          name: 'upfile',
          accept: "audio/*",
          data: {
              withStatus: true
          },
          headers: {
              'X-Requested-With': null,
          },
          onProgress: null,
      };





    return (
      <div id="wrap">
        <Breadcrumb className="breadcrumb">
          <Breadcrumb.Item>
            <Link to={`/question/manager/index`}>
              
              <span>题库列表</span>
            </Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
              {location.hash.indexOf('detail') > 0 ? '资讯详情' : '新增资讯'}
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="content">


            <Form onSubmit={this.handleSubmit}>
                <FormItem
                    {...formItemLayout}
                    label='题目'
                    hasFeedback
                >
                    {getFieldDecorator('title', {
                        rules: [{ required: true, message: '请输入', whitespace: true }],
                        initialValue:location.hash.indexOf('add') > 0 ? undefined : detail.title
                    })(
                        <Input/>
                    )}
                </FormItem>


                

              <FormItem
                  {...formItemLayout}
                  label='图片'
                  hasFeedback
              >
                  {getFieldDecorator('pic', {
                      rules: [{  message: '请上传一张图片' }],
                      getValueFromEvent: this.normFile.bind(this),
                      initialValue:location.hash.indexOf('add') > 0 ? undefined : detail.pic
                  })(

                    <Upload
                        {...props}
                        >
                        {
                            detail.cover ?
                            <img src={detail.cover} alt="" className="avatar "/> :
                            <Icon type="plus" className="avatar-uploader-trigger"/>
                        }
                    </Upload>
                  )}
              </FormItem>

              

                <FormItem
                    {...formItemLayout}
                    label='答案'
                    hasFeedback
                >
                    {getFieldDecorator('answer', {
                         rules: [{ required: true, message: '请输入详情' }],
                        initialValue:location.hash.indexOf('add') > 0 ? undefined : detail.answer
                    })(
                        <Input  />
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label='选项A:'
                    hasFeedback
                >
                    {getFieldDecorator('options', {
                        rules: [{ required: true, message: '请输入', whitespace: true }],
                        initialValue:location.hash.indexOf('add') > 0 ? undefined : detail.options
                    })(
                        <Input />
                        
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label='选项B:'
                    hasFeedback
                >
                    {getFieldDecorator('options', {
                        rules: [{ required: true, message: '请输入', whitespace: true }],
                        initialValue:location.hash.indexOf('add') > 0 ? undefined : detail.options
                    })(
                        <Input />
                        
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label='选项C:'
                    hasFeedback
                >
                    {getFieldDecorator('options', {
                        rules: [{ required: true, message: '请输入', whitespace: true }],
                        initialValue:location.hash.indexOf('add') > 0 ? undefined : detail.options
                    })(
                        <Input />
                        
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label='选项D:'
                    hasFeedback
                >
                    {getFieldDecorator('options', {
                        rules: [{ required: true, message: '请输入', whitespace: true }],
                        initialValue:location.hash.indexOf('add') > 0 ? undefined : detail.options
                    })(
                        <Input />
                        
                    )}
                </FormItem>

                <FormItem {...tailFormItemLayout}>
                    <Button type="primary" htmlType="submit" size="large"
                            loading={this.state.buttonLoading}>{this.state.buttonLoading ? '正在提交...' : '提交'}</Button>
                </FormItem>
            </Form>


            <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
        </div>
      </div>
    )

  }
}
const Detail = Form.create()(SingerDetail)
export default Detail